package com.netease.nie.facade;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.netease.nie.base.cache.redis.Redis;
import com.netease.nie.base.cdn.CDNProperties;
import com.netease.nie.base.exceptions.BusinessException;
import com.netease.nie.base.utils.CopyUtils;
import com.netease.nie.base.utils.CustomDateFormatUtils;
import com.netease.nie.base.utils.JsonUtils;
import com.netease.nie.common.CommonBusinessTools;
import com.netease.nie.constants.BusinessConstants;
import com.netease.nie.constants.CachePrefixConstants;
import com.netease.nie.constants.CustomGoodsConstants;
import com.netease.nie.constants.DisplayTypeConstants;
import com.netease.nie.constants.GoodsTypeStants;
import com.netease.nie.dto.CustomGoodsPrizeOrdersTraceInfoDto;
import com.netease.nie.dto.ExchangeGoodsDetailDto;
import com.netease.nie.dto.ExchangeGoodsExchangeDto;
import com.netease.nie.dto.ExchangeGoodsInfoDto;
import com.netease.nie.dto.GoodsInfoDto;
import com.netease.nie.dto.GoodsInfoImageDto;
import com.netease.nie.dto.LogisticsDto;
import com.netease.nie.dto.OrdersAddressDto;
import com.netease.nie.dto.OrdersTraceDto;
import com.netease.nie.model.ExchangeCode;
import com.netease.nie.model.ExchangeGoodsInfoExtend;
import com.netease.nie.model.Orders;
import com.netease.nie.service.CategoryService;
import com.netease.nie.service.ExchangeCodeService;
import com.netease.nie.service.ExchangeGoodsInfoExtendService;
import com.netease.nie.service.ExchangeGoodsInfoService;
import com.netease.nie.service.GoodsInfoImageService;
import com.netease.nie.service.GoodsInfoService;
import com.netease.nie.service.LogisticsService;
import com.netease.nie.service.OrderService;
import com.netease.nie.service.OrdersAddressService;
import com.netease.nie.service.OrdersTraceService;

/**
 * 
 * @author wwbn3695
 * @createDate May 31st,2016
 * 
 */
@Service
public class ExchangeGoodsFacadeImpl extends CommonBusinessTools implements ExchangeGoodsFacade {

	private static final String GOODS_DETAIL_PREFIX = CachePrefixConstants.GoodsPrefix.GOODS_DETAIL_PREFIX;
	private static final String GOODS_EXCHANGE_PREFIX = CachePrefixConstants.GoodsPrefix.GOODS_EXCHANGE_PREFIX;
	private static final String GOODS_STOCK_PREFIX = CachePrefixConstants.GoodsPrefix.GOODS_STOCK_PREFIX;
	private static final String GOODS_CATEGORY_TOP_GOODS_LIST_PREFIX = CachePrefixConstants.GoodsPrefix.GOODS_CATEGORY_TOP_GOODS_LIST_PREFIX;

	private static final String GOODS_CATEGORY_LIST_KEY = "Goods_Category_List";

	@Autowired
	private GoodsInfoService goodsInfoService;
	
	@Autowired
	private ExchangeGoodsInfoService exchangeGoodsInfoService;

	@Autowired
	private ExchangeGoodsInfoExtendService exchangeGoodsInfoExtendService;

	@Autowired
	private GoodsInfoImageService goodsInfoImageService;

	@Autowired
	private CategoryService goodsCategoryService;

	@Autowired
	private ExchangeCodeService exchangeCodeService;

	@Autowired
	private OrderService orderService;
	
	@Autowired
	private OrdersAddressService ordersAddressService;
	
	@Autowired
	private OrdersTraceService ordersTraceService;
	
	@Autowired
	private LogisticsService logisticsService;
	
	@Autowired
	private CDNProperties cdnProperties;

	@Autowired
	private Redis redis;

	public ExchangeGoodsDetailDto queryGoodsDetailDtoById(int id) {
		String exchangeGoodsDetailKey = GOODS_DETAIL_PREFIX + id;
		String exchangeGoodsDetailJson = redis.get(exchangeGoodsDetailKey);
		ExchangeGoodsDetailDto exchangeGoodsDetailDto = null;
		if (StringUtils.isBlank(exchangeGoodsDetailJson)) {
			ExchangeGoodsInfoDto exchangeGoodsInfoDto = exchangeGoodsInfoService.queryExchangeGoodsInfoById(id);
			GoodsInfoDto goodsInfoDto = goodsInfoService.queryGoodsInfoById(id);
			ExchangeGoodsInfoExtend exchangeGoodsInfoExtend = exchangeGoodsInfoExtendService
					.queryGoodsIntroductionById(id);
			List<GoodsInfoImageDto> goodsInfoImageDtos = goodsInfoImageService
					.queryGoodsInfoImageDtosByGoodsId(exchangeGoodsInfoDto.getGoodsId());         //图片的查询跟抽象商品关联
			exchangeGoodsDetailDto = new ExchangeGoodsDetailDto();
			exchangeGoodsDetailDto.setId(exchangeGoodsInfoDto.getId());
			exchangeGoodsDetailDto.setExchangeObjectId(exchangeGoodsInfoDto
					.getExchangeObjectId());
			exchangeGoodsDetailDto.setGoodsInfoImageDtos(goodsInfoImageDtos);
			exchangeGoodsDetailDto.setSpecialIntroduction(exchangeGoodsInfoExtend.getSpecialIntroduction());
			exchangeGoodsDetailDto.setIntroduction(goodsInfoDto.getIntroduction());
			exchangeGoodsDetailDto.setPrice(exchangeGoodsInfoDto.getPrice());

			exchangeGoodsDetailDto.setPutOffTime(exchangeGoodsInfoDto.getPutOffTime());
			exchangeGoodsDetailDto.setPutOnTime(exchangeGoodsInfoDto.getPutOnTime());
			exchangeGoodsDetailDto.setTitle(exchangeGoodsInfoDto.getTitle());
			exchangeGoodsDetailDto.setSubTitle(exchangeGoodsInfoDto.getSubTitle());
			exchangeGoodsDetailDto.setGoodsType(exchangeGoodsInfoDto.getGoodsType());
			exchangeGoodsDetailDto.setThumbnailUrl(exchangeGoodsInfoDto.getThumbnailUrl());

			exchangeGoodsDetailDto.setValidDate(exchangeGoodsInfoDto.getValidDate());
			redis.set(exchangeGoodsDetailJson, JsonUtils.obj2String(exchangeGoodsDetailDto));
		} else {
			exchangeGoodsDetailDto = JsonUtils.getClazz(exchangeGoodsDetailJson,
					ExchangeGoodsDetailDto.class);
		}

		// 从缓存中取出实时库存
		String goodsStockKey = GOODS_STOCK_PREFIX + id;
		String stockTemp = redis.get(goodsStockKey);
		if (StringUtils.isNotBlank(stockTemp))
			exchangeGoodsDetailDto.setStock(Integer.valueOf(stockTemp));
		else {
			exchangeGoodsDetailDto.setStock(0);
		}
		
		//置换商品图片
		replaceGoodsInfoImageDto(exchangeGoodsDetailDto.getGoodsInfoImageDtos(), DisplayTypeConstants.WAP.getCode());
		exchangeGoodsDetailDto.setThumbnailUrl(cdnProperties.getCdnPrefix() + exchangeGoodsDetailDto.getThumbnailUrl());
		return exchangeGoodsDetailDto;
	}

	public ExchangeGoodsExchangeDto queryGoodsExchangeDtoById(Long orderId, Long userId) {
		String goodsExchangeKey = GOODS_EXCHANGE_PREFIX + orderId;
		String goodsExchangeJson = redis.get(goodsExchangeKey);
		ExchangeGoodsExchangeDto exchangeGoodsExchangeDto = null;
		if (StringUtils.isBlank(goodsExchangeJson)) {
			Orders orders = orderService.getOrderByOrderIdAndUserId(orderId, userId);
			if (orders == null)
				throw new BusinessException(BusinessConstants.ORDER_NOT_EXISTS.getCode(),
						"订单不存在！");
			if (orders.getCustomGoodsCode() != CustomGoodsConstants.EXCHANGE.getCode())
				throw new BusinessException(BusinessConstants.ORDER_NOT_EXISTS.getCode(),
						"必须是兑换商品的订单！");
			ExchangeGoodsInfoDto exchangeGoodsInfoDto = exchangeGoodsInfoService.queryExchangeGoodsInfoByIdWithoutPutOnStatus(orders.getCustomGoodsId());
			//GoodsInfoImage goodsInfoImage = goodsInfoImageService.queryCoverGoodsImageByGoodsId(exchangeGoodsInfoDto.getGoodsId());          //查找图片必须是抽象商品字段
				
			Integer goodsType = exchangeGoodsInfoDto.getGoodsType();
			exchangeGoodsExchangeDto = new ExchangeGoodsExchangeDto();
			if (orders != null) {
				//兑换日期
				exchangeGoodsExchangeDto.setExchangeTime(CustomDateFormatUtils.getyyyyMMddHHmmssStr(orders.getCreateTime()));
				//订单流水号
				exchangeGoodsExchangeDto.setOrderId(orders.getId());
				//订单中的用户id
				exchangeGoodsExchangeDto.setUserId(orders.getUserId());
			}
			CopyUtils.copy(exchangeGoodsExchangeDto, exchangeGoodsInfoDto);
			exchangeGoodsExchangeDto.setGoodsId(exchangeGoodsInfoDto.getId());
			// 设置到期时间   实物商品无到期时间	
			if (exchangeGoodsInfoDto.getValidDate() != null) {			
				exchangeGoodsExchangeDto.setExpireDate(exchangeGoodsInfoDto.getValidDate()); //TODO
			}
			// 兑换类型是兑换码
			if (goodsType == GoodsTypeStants.REDEEM_CODE.getCode()) {
				ExchangeCode exchangeCode = exchangeCodeService.queryExchangeCodeById(orders.getExchangeCodeId());
				exchangeGoodsExchangeDto.setExchangeCode(exchangeCode.getExchangeCode());
				exchangeGoodsExchangeDto.setQrcodeUrl(exchangeCode.getQrcodeUrl());
			}
			// 兑换类型是电子凭证
			else if (goodsType == GoodsTypeStants.E_CREDENTIAL.getCode()) {
				GoodsInfoDto goodsInfoDto = goodsInfoService.queryGoodsInfoById(exchangeGoodsInfoDto.getGoodsId());
				exchangeGoodsExchangeDto.setElectronicCredentialUrl(goodsInfoDto.getElectronicCredentialUrl());
			}
			// 兑换类型是实物商品
			else if (goodsType == GoodsTypeStants.ENTITY.getCode()) {
				OrdersAddressDto ordersAddressDto = ordersAddressService.queryOrdersAddressByOrdersId(orders.getId());
				if (ordersAddressDto != null)
					exchangeGoodsExchangeDto.setOrdersAddressDto(ordersAddressDto);
				List<OrdersTraceDto> ordersTraceDtoList = ordersTraceService.queryOrdersTraceListByOrdersId(orders.getId());
				if (ordersTraceDtoList != null){
					List<CustomGoodsPrizeOrdersTraceInfoDto> customGoodsPrizeOrdersTraceInfoDtoList = 
							generateCustomGoodsPrizeOrdersTraceInfoDtoList(ordersTraceDtoList);
					
					exchangeGoodsExchangeDto.setOrdersTraceDtos(customGoodsPrizeOrdersTraceInfoDtoList);
				}
				LogisticsDto logisticsDto = logisticsService.queryLogisticsByOrdersId(orders.getId());
				if (logisticsDto != null)
					exchangeGoodsExchangeDto.setLogisticsDto(logisticsDto);
			}
			
			//设置商品图片
			exchangeGoodsExchangeDto.setImageWapUrl(exchangeGoodsInfoDto.getThumbnailWapUrl());
			
			redis.set(goodsExchangeKey, JsonUtils.obj2String(exchangeGoodsExchangeDto));
			
		} else
			exchangeGoodsExchangeDto = JsonUtils.getClazz(goodsExchangeJson, ExchangeGoodsExchangeDto.class);
		
		if (!exchangeGoodsExchangeDto.getUserId().equals(userId))
			throw new BusinessException(BusinessConstants.USER_ID_ILLEGAL.getCode(),"请求非法！");		
		// 替换商品图片
		replaceGoodsExchangeDto(exchangeGoodsExchangeDto, DisplayTypeConstants.WAP.getCode());
		return exchangeGoodsExchangeDto;
	}
	
	private List<CustomGoodsPrizeOrdersTraceInfoDto> generateCustomGoodsPrizeOrdersTraceInfoDtoList(List<OrdersTraceDto> ordersTraceDtoList) {
		if (ordersTraceDtoList != null && !ordersTraceDtoList.isEmpty()) {
			List<CustomGoodsPrizeOrdersTraceInfoDto> customGoodsPrizeOrdersTraceInfoDtoList = new ArrayList<>();
			int ordersTraceDtoListSize = ordersTraceDtoList.size();
			OrdersTraceDto ordersTraceDto = null;
			CustomGoodsPrizeOrdersTraceInfoDto customGoodsPrizeOrdersTraceInfoDto = null;
			for (int i = 0; i < ordersTraceDtoListSize; i++) {
				ordersTraceDto = ordersTraceDtoList.get(i);
				customGoodsPrizeOrdersTraceInfoDto = new CustomGoodsPrizeOrdersTraceInfoDto();
				CopyUtils.copy(customGoodsPrizeOrdersTraceInfoDto, ordersTraceDto);
				customGoodsPrizeOrdersTraceInfoDto.setCreateTimeStr(CustomDateFormatUtils.getyyyyMMddHHmmssStr(ordersTraceDto.getCreateTime()));
				customGoodsPrizeOrdersTraceInfoDtoList.add(customGoodsPrizeOrdersTraceInfoDto);
			}
			return customGoodsPrizeOrdersTraceInfoDtoList;
		}
		return Collections.emptyList();
	}
}
